package dhy.com.tomcat.three.param;

import dhy.com.tomcat.three.error.StringManager;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 对HashMap做的增强在于多加了一把锁,用来控制用户是否可以修改请求参数的值
 * </P>
 *
 * @author 大忽悠
 * @create 2022/3/9 22:10
 */
public class ParameterMap extends HashMap {
    /**
     * 防止用户对请求参数的值进行修改
     */
    private boolean locked = false;

    public ParameterMap() {
        super();
    }

    public ParameterMap(int initialCapacity) {
        super(initialCapacity);
    }

    public ParameterMap(int initialCapacity, float loadFactor) {
        super(initialCapacity, loadFactor);
    }

    public ParameterMap(Map map) {
        super(map);
    }

    public boolean isLocked() {
        return locked;
    }

    public void setLocked(boolean locked) {
        this.locked = locked;
    }

    private static final StringManager sm =
            //传入包名
            StringManager.getManager("dhy.com.tomcat.three.param");

    @Override
    public void clear() {
        checkLocked();
        super.clear();
    }

    @Override
    public Object put(Object key, Object value) {
        checkLocked();
        return super.put(key, value);
    }

    @Override
    public void putAll(Map m) {
        checkLocked();
        super.putAll(m);
    }


    @Override
    public Object remove(Object key) {
       checkLocked();
        return super.remove(key);
    }

    /**
     * 检查是否上锁了
     */
    private void checkLocked() {
        if (locked) {
            throw new IllegalStateException
                    (sm.getString("parameterMap.locked"));
        }
    }
}
